<?php
class LocationUtility
{
    public static function getById($locationId)
    {
        return LocationModel::model()->findByPk($locationId);
    }
    
    public static function add($id, $name, $latitude, $longitude)
    {
        // map to city
        $country = self::getCounty($latitude, $longitude);
        $city = LocationModel::model()->getNearestCity($latitude, $longitude, $country);

        // add
        $location = new LocationModel();
        $location->id = $id;
        $location->name = $name;
        $location->latitude = $latitude;
        $location->longitude = $longitude;
        $location->city_id = $city['city_id'];
        $location->distance = $city['distance'];
        $location->save();
        
        return $location;
    }

    public static function calcDistance($lat1, $lng1, $lat2, $lng2)
    {
        $lat1 = deg2rad($lat1);
        $lat2 = deg2rad($lat2);
        $theta = deg2rad($lng1 - $lng2);
        $dist = sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta);
        $dist = acos($dist);
        $dist = rad2deg($dist);
        return intval($dist * 60 * 1.1515 * 1.609344);
    }

    public static  function getCounty($latitude, $longitude)
    {
        $url = 'http://maps.google.com/maps/api/geocode/json?latlng=%s,%s&sensor=false';
        $url = sprintf($url, $latitude, $longitude);
        $get = file_get_contents($url);
        $geoData = json_decode($get);
        if(isset($geoData->results[0]))
        {
            foreach($geoData->results[0]->address_components as $addressComponent)
            {
                if(in_array('country', $addressComponent->types))
                {
                    return $addressComponent->short_name;
                }
            }
        }
        return '';
    }
}